//
//  DHBrandViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/20.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHBrandViewController.h"
#import "DHBrandProductCollectionCell.h"
#import "DHS2_ProductDetailController.h"

@interface DHBrandViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *logoImgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentHeightLayout;
@property (weak, nonatomic) IBOutlet UIScrollView *tableViewScrollvIEW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineViewLeftLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSafeAreaLayout;

@property (assign, nonatomic) NSInteger pageIndex;

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) UIWebView *infoView;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NSDictionary *brandInfo;

@property (strong, nonatomic) NSString *brandID;
@property (weak, nonatomic) IBOutlet UIButton *likeButton;

@property (assign, nonatomic) BOOL isLiked;
@property (weak, nonatomic) IBOutlet UIScrollView *allScrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *allContentHeightLayout;

@end

@implementation DHBrandViewController

- (instancetype)initWithBrandID:(NSString *)brandId
{
    self = [super init];
    if (self) {
        self.brandID = brandId;
    }
    return self;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([UIDevice systemVersion] < 11) {
        self.topSafeAreaLayout.constant = 64;
    }
    
    self.contentHeightLayout.constant = 2000;
    
    self.tableViewScrollvIEW.contentSize = CGSizeMake(kScreenWidth * 2, self.tableViewScrollvIEW.height);
    
    [self.likeButton bk_addEventHandler:^(id sender) {
        if (self.isLiked) {
            [self.likeButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
            [[DHNetAPIClient shareDHNetAPIClient] request_brand_collectWithParams:@{@"brand_id":self.brandID,@"collect":[NSNumber numberWithBool:!self.isLiked]} andBlock:^(id data, NSError *error) {
                self.isLiked = !self.isLiked;
            }];
        }else{
            [self.likeButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
            [[DHNetAPIClient shareDHNetAPIClient] request_brand_collectWithParams:@{@"brand_id":self.brandID,@"collect":[NSNumber numberWithBool:!self.isLiked]} andBlock:^(id data, NSError *error) {
                self.isLiked = !self.isLiked;
            }];
        }
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self initView];
    [self loadProduct];
    [self loadInfo];
    
    self.allContentHeightLayout.constant = 2000;
    self.allScrollView.contentSize = CGSizeMake(self.allScrollView.width, 2000);
}

- (void)initView{
    UICollectionViewFlowLayout *layout =  [[UICollectionViewFlowLayout alloc] init];
    self.collectionView =[[UICollectionView alloc] initWithFrame:CGRectMake(5, 0, self.tableViewScrollvIEW.width - 10, self.tableViewScrollvIEW.height) collectionViewLayout: layout];
    [self.collectionView registerNib:[UINib nibWithNibName:@"DHBrandProductCollectionCell" bundle:nil] forCellWithReuseIdentifier:kDHBrandProductCollectionCell];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadProduct)];
    self.collectionView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProduct)];
    [self.tableViewScrollvIEW addSubview:self.collectionView];
    
    self.infoView = [[UIWebView alloc] initWithFrame:CGRectMake(self.collectionView.right, 0, self.tableViewScrollvIEW.width, self.tableViewScrollvIEW.height)];
    self.infoView.backgroundColor = [UIColor whiteColor];
    [self.tableViewScrollvIEW addSubview:self.infoView];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.collectionView.frame = CGRectMake(0, 0, self.tableViewScrollvIEW.width, self.tableViewScrollvIEW.height);
    self.infoView.frame = CGRectMake(self.collectionView.right, 0, self.tableViewScrollvIEW.width, self.tableViewScrollvIEW.height);
}

- (void)loadProduct{
    self.pageIndex = 0;
    [self.collectionView.mj_footer resetNoMoreData];
    NSString *sex = [GlobalManager shareGlobalManager].user.sex? : [[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX];
    [[DHNetAPIClient shareDHNetAPIClient] request_productsWithParams:@{@"brand_id":self.brandID,@"pageIndex":@(self.pageIndex),@"pageSize":@(20)} andBlock:^(id data, NSError *error) {
        [self.collectionView.mj_header endRefreshing];
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:[data objectForKey:@"products"]];
        if (self.dataArray.count < 20) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        self.pageIndex += 1;
        [self.collectionView reloadData];
    }];
}

- (void)loadMoreProduct{
    NSString *sex = [GlobalManager shareGlobalManager].user.sex? : [[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX];
    [[DHNetAPIClient shareDHNetAPIClient] request_productsWithParams:@{@"brand_id":self.brandID,@"pageIndex":@(self.pageIndex),@"pageSize":@(20)} andBlock:^(id data, NSError *error) {
        [self.collectionView.mj_footer endRefreshing];
        [self.dataArray addObjectsFromArray:[data objectForKey:@"products"]];
        if (self.dataArray.count < 20 * (self.pageIndex + 1)) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        self.pageIndex += 1;
        [self.collectionView reloadData];
    }];
}

- (void)loadInfo{
    [[DHNetAPIClient shareDHNetAPIClient] request_brands_detailWithParams:@{@"brand_id":self.brandID} AndBlock:^(id data, NSError *error) {
        self.brandInfo = [data objectForKey:@"brand"];
        [self updateInfoUI];
    }];
}

- (void)updateInfoUI{
    [self.logoImgView dh_setImageURLString:[self.brandInfo objectForKey:@"cover"]];
    self.title = [self.brandInfo objectForKey:@"name"];
    [self.infoView loadHTMLString:[self.brandInfo objectForKey:@"description"] baseURL:nil];
    
    self.titleLabel.text = [self.brandInfo objectForKey:@"name"];
    self.isLiked = [[self.brandInfo objectForKey:@"collected"] boolValue];
    
    if (self.isLiked) {
        [self.likeButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
    }else{
        [self.likeButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
    }
}

- (IBAction)productAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    self.tableViewScrollvIEW.contentOffset = CGPointMake(0, 0);
    self.lineViewLeftLayout.constant = btn.left + 10;
}

- (IBAction)infoAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    self.tableViewScrollvIEW.contentOffset = CGPointMake(self.tableViewScrollvIEW.width, 0);
    self.lineViewLeftLayout.constant = btn.left + 10;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDataSource and UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DHBrandProductCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHBrandProductCollectionCell forIndexPath:indexPath];
    [cell uploadCell:self.dataArray[indexPath.row]];
    cell.leftPriceLabel.adjustsFontSizeToFitWidth = YES;
    cell.rightPriceLabel.adjustsFontSizeToFitWidth = YES;
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){109,200};
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *model = [self.dataArray objectAtIndex:indexPath.row];
    DHS2_ProductDetailController *vc = [[DHS2_ProductDetailController alloc] initWithProduct:model];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x / self.tableViewScrollvIEW.width == 0) {
        [self productAction:nil];
    }else if (scrollView.contentOffset.x / self.tableViewScrollvIEW.width == 1){
        [self infoAction:nil];
    }
}

@end
